package main

import (
    "net/http"
    "encoding/json"
    "io/ioutil"
    "bytes"
    "unsafe"
)

func postCaToServer(dCer string, dKey string, state int) {

    data := make(map[string]interface{})
    if state == 1 {
        data["public_key"] = dCer
        data["private_key"] = dKey
        data["state"] = 1
    }else
    {
        data["state"] = 3
    }
    data["uid"] = uid
    data["name"] = domain
    if id != -1 {
        data["id"] = id
    }

    mainlog.Println("\ncer:", dCer, "\nkey:" ,dKey, "\nuid:", uid, "\ndomain:", domain, "\nstate:", state)

    bytesData, err := json.Marshal(data)
    if err != nil {
        mainlog.Println("json.Marshal:", err)
        return
    }

    reader := bytes.NewReader(bytesData)
    request, err := http.NewRequest("PUT", api, reader)
    if err != nil {
        mainlog.Println("http.NewRequest:", err)
        return
    }

    request.Header.Set("Content-Type", "application/json;charset=UTF-8")
    request.Header.Add("Accept", "application/json")
    request.Header.Add("Authorization", "Bearer" + token)
    client := http.Client{}
    resp, err := client.Do(request)
    if err != nil {
        mainlog.Println("client.Do:", err)
        return
    }

    respBytes, err := ioutil.ReadAll(resp.Body)

    resp.Body.Close()

    if err != nil {
        mainlog.Println("ioutil.ReadAll:", err)
        return
    }

    //byte数组直接转成string，优化内存
    str := (*string)(unsafe.Pointer(&respBytes))
    mainlog.Println(*str)
}